package dataflowScheme.diagram.edit.commands;

import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.gmf.runtime.emf.type.core.commands.CreateElementCommand;
import org.eclipse.gmf.runtime.emf.type.core.requests.CreateElementRequest;
import org.eclipse.gmf.runtime.notation.View;

import dataflowScheme.Block;
import dataflowScheme.PE;
import dataflowScheme.PortSet;
import dataflowScheme.Storage;
import dataflowScheme.Task;

/**
 * @generated
 */
public class PortSetCreateCommand extends CreateElementCommand {

	/**
	 * @generated
	 */
	public PortSetCreateCommand(CreateElementRequest req) {
		super(req);
	}

	/**
	 * @generated
	 */
	protected EObject getElementToEdit() {
		EObject container = ((CreateElementRequest) getRequest())
				.getContainer();
		if (container instanceof View) {
			container = ((View) container).getElement();
		}
		return container;
	}

	/**
	 * @generated
	 */
	protected EClass getEClassToEdit() {
		return dataflowScheme.DataflowSchemePackage.eINSTANCE.getPE();
	}

	/**
	 * find max used id
	 * @param pe
	 * @return
	 */
	private int getPEmaxPortSetID(PE pe){
		int maxId = 0;
		for(PortSet ps : pe.getPortSet()){
			if(ps.getId() > maxId){
				maxId = ps.getId();
			}
		}
		return maxId;
	}
	
	/**
	 * check ids of all portsets with the same name
	 * @param storage
	 * @return
	 */
	private int getPEmaxPortSetIDforStorage(Storage storage){
		EList<PE> entities = ((Block)storage.eContainer()).getEntity();
		
		int maxId = getPEmaxPortSetID(storage);
		for(PE pe: entities){
			if(pe instanceof Storage){
				if(pe != storage){
					if(pe.getName().equals(storage.getName())){
						//we have the same kind of storage
						int sameStorageMaxID = getPEmaxPortSetID(pe);
						if(maxId < sameStorageMaxID){
							maxId = sameStorageMaxID;
						}
					}
				}
			}
		}
		
		return maxId;
	}
	
	protected EObject doDefaultElementCreation() {
		EObject result = super.doDefaultElementCreation();
		
		if(result instanceof PortSet){
			PortSet ps = (PortSet)result;
			
			EObject par = result.eContainer();
			if(par instanceof Task){
				ps.setId(getPEmaxPortSetID((Task)par) + 1);
			} else if(par instanceof Storage){
				ps.setId(getPEmaxPortSetIDforStorage((Storage)par) + 1);
			}
		}
		return result;
	}

}
